<template>
    <div class="ai-chat">
      <van-nav-bar title="AI 助手" left-arrow @click-left="$router.back()" />
   
      <div class="chat-container">
        <div class="chat-history">
          <div v-for="(message, index) in messages" :key="index"
            :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'ai' }">
            <div class="message-content" v-html="message.content"></div>
          </div>
        </div>
      </div>
   
      <div class="input-area">
        <van-field v-model="question" placeholder="请输入你的问题" :disabled="loading" @keyup.enter="handleSend">
          <template #button>
            <van-button :loading="loading" type="primary" size="small" @click="handleSend">
              发送
            </van-button>
          </template>
        </van-field>
      </div>
    </div>
   </template>
   
   <script setup>
   import { ref, onMounted, onUnmounted, nextTick } from 'vue'
   import { showToast } from 'vant'
   import { marked } from 'marked'
   import hljs from 'highlight.js'
   import 'highlight.js/styles/github.css'
   
   const question = ref('')
   const loading = ref(false)
   const currentResponse = ref('')
   const messages = ref([])
   let eventSource = null
   
   // 配置 marked
   marked.setOptions({
    highlight: function (code, lang) {
      return hljs.highlightAuto(code).value
    }
   })
   
   const handleSend = async () => {
    if (!question.value.trim()) {
      showToast('请输入问题')
      return
    }
   
    try {
      loading.value = true
      // 添加用户问题到聊天记录
      messages.value.push({ role: 'user', content: question.value })
      // 清空输入框
      const inputValue = question.value
      question.value = ''
      currentResponse.value = '' // 重置当前响应

      // 创建一个初始的 AI 回复消息
      messages.value.push({ role: 'ai', content: '' })

      // 创建 EventSource 连接
      eventSource = new EventSource(`/api/auth/chatStream?question=${encodeURIComponent(inputValue)}`)
   
      eventSource.onmessage = (event) => {
        const text = event.data
        currentResponse.value += text
        // 更新最后一条 AI 消息的内容
        messages.value[messages.value.length - 1].content = marked(currentResponse.value)
        // 滚动到底部
        nextTick(() => {
          const chatHistory = document.querySelector('.chat-history')
          chatHistory.scrollTop = chatHistory.scrollHeight
        })
      }
   
      eventSource.onerror = (error) => {
        console.error('SSE Error:', error)
        eventSource.close()
        loading.value = false
        if (!currentResponse.value) {
          showToast('获取回答失败')
        }
      }
   
      // 监听连接关闭
      eventSource.addEventListener('done', () => {
        eventSource.close()
        loading.value = false
      })
   
    } catch (error) {
      console.error('Request error:', error)
      showToast('获取回答失败')
      loading.value = false
    }
   }
   
   // 组件卸载时关闭 EventSource 连接
   onUnmounted(() => {
    if (eventSource) {
      eventSource.close()
    }
   })
   
   // 组件加载完成后滚动到底部
   onMounted(() => {
    const chatHistory = document.querySelector('.chat-history');
    chatHistory.scrollTop = chatHistory.scrollHeight;
   });
   
   </script>
   
   <style scoped lang="scss">
   .ai-chat {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #f7f7f7;
   
    .chat-container {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
   
      .chat-history {
        display: flex;
        flex-direction: column;
   
        .user-message,
        .ai-message {
          margin-bottom: 12px;
          display: flex;
          justify-content: flex-start;
        }
   
        .user-message {
          justify-content: flex-end;
        }
   
        .message-content {
          background: white;
          border-radius: 8px;
          padding: 16px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
          max-width: 70%;
   
          :deep(.markdown-body) {
            font-size: 14px;
            line-height: 1.6;
   
            pre {
              background: #f6f8fa;
              padding: 16px;
              border-radius: 6px;
              overflow-x: auto;
            }
   
            code {
              font-family: Consolas, Monaco, 'Andale Mono', monospace;
            }
   
            h3 {
              margin-top: 24px;
              margin-bottom: 16px;
              font-size: 16px;
              font-weight: 600;
            }
   
            ul,
            ol {
              padding-left: 20px;
            }
   
            p {
              margin: 12px 0;
            }
          }
        }
      }
   
    }
   
    .input-area {
      padding: 12px;
      background: white;
      border-top: 1px solid #eee;
   
      :deep(.van-field) {
        background: #f5f5f5;
        border-radius: 4px;
        padding: 4px 8px;
      }
   
      .van-button {
        margin-left: 8px;
      }
    }
   }
   </style>
   
   